import React, { useState, useMemo } from 'react';
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Table,
  Select,
  Avatar,
  Dropdown,
  Menu,
  Tooltip,
  Space,
  Checkbox,
} from 'antd';
import {
  ColumnHeightOutlined,
  FullscreenOutlined,
  RedoOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import {
  useFormTable,
  useDebounceFn,
  useFullscreen,
  useSelections,
} from '@umijs/hooks';
import { queryList } from '@/services/umiHooks';

const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    width: 50,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 50,
    render: (text: any) => <span>{text === 'male' ? '男' : '女'}</span>,
  },
  {
    title: '头像',
    dataIndex: 'picture',
    width: 50,
    render: (text: any) => <Avatar shape="square" size={50} src={text} />,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 50,
  },
];

const { Option } = Select;

const useFormTablePage = () => {
  const [size, setSize] = useState<any>(['large']);

  const [form] = Form.useForm();

  // 设置全屏
  const { setFull } = useFullscreen<HTMLElement>({
    dom: (): any => document.getElementById('FullScreen-Table'),
  });

  // 请求数据
  const { tableProps, search, refresh } = useFormTable(
    ({ current, pageSize }, formData: Object) =>
      queryList({
        ...formData,
        results: pageSize,
        inc: 'name,email,picture,login,gender',
        page: current,
      }),
    {
      defaultPageSize: 5,
      formatResult: response => {
        const { results } = response;
        const newResponse: Array<{}> = [];
        results.forEach((item: any) => {
          newResponse.push({
            id: item.login.uuid,
            name: item.name.first,
            picture: item.picture.large,
            gender: item.gender,
            email: item.email,
          });
        });
        return Object.assign({}, { total: 100, list: newResponse });
      },
      form,
    },
  );

  const { type, changeType, submit, reset } = search;

  const columnsTitle = useMemo(() => {
    return columns.map(o => o.title);
  }, [columns]);

  // 选择列
  const {
    selected,
    allSelected,
    isSelected,
    toggle,
    toggleAll,
    partiallySelected,
  } = useSelections(columnsTitle, columnsTitle);

  // 函数防抖
  const { run } = useDebounceFn(submit, 1000);

  // 密度下拉菜单
  const menu = (
    <Menu selectedKeys={size} onClick={({ key }) => setSize([key])}>
      <Menu.Item key="large">默认</Menu.Item>
      <Menu.Item key="middle">中等</Menu.Item>
      <Menu.Item key="small">紧凑</Menu.Item>
    </Menu>
  );

  // 列设置下拉菜单
  const columnsMenu = (
    <Menu>
      <Menu.Item key="all">
        <Checkbox
          checked={allSelected}
          onClick={toggleAll}
          indeterminate={partiallySelected}
        >
          全选
        </Checkbox>
      </Menu.Item>
      {columns.map(item => {
        return (
          <Menu.Item key={item.title}>
            <Checkbox
              checked={isSelected(item.title)}
              onClick={() => toggle(item.title)}
            >
              {item.title}
            </Checkbox>
          </Menu.Item>
        );
      })}
    </Menu>
  );

  // 计算后的columns
  const newColumns = useMemo(() => {
    return columns.filter((item: any) => selected.includes(item.title));
  }, [selected]);

  const advanceSearchForm = (
    <div>
      <Form form={form}>
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item label="姓名" name="name">
              <Input placeholder="请输入姓名" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="性别" name="gender">
              <Select
                style={{ width: '100%', marginRight: 16 }}
                onChange={submit}
                placeholder="请选择性别"
              >
                <Option value="">全部</Option>
                <Option value="male">男</Option>
                <Option value="female">女</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="邮箱" name="email">
              <Input placeholder="请输入邮箱" />
            </Form.Item>
          </Col>
        </Row>
        <Row justify="space-between">
          <Col span={12}>
            <Form.Item>
              <Button type="primary" onClick={submit}>
                搜索
              </Button>
              <Button onClick={reset} style={{ marginLeft: 16 }}>
                重置
              </Button>
              <Button type="link" onClick={changeType}>
                返回
              </Button>
            </Form.Item>
          </Col>
          <Col
            span={12}
            style={{ display: 'flex', justifyContent: 'flex-end' }}
          >
            <Form.Item>
              <Space size={10}>
                <Tooltip title="密度">
                  <Dropdown overlay={menu} trigger={['click']}>
                    <ColumnHeightOutlined style={{ fontSize: 18 }} />
                  </Dropdown>
                </Tooltip>
                <Tooltip title="全屏">
                  <FullscreenOutlined
                    style={{ fontSize: 18, cursor: 'pointer' }}
                    onClick={setFull}
                  />
                </Tooltip>
                <Tooltip title="刷新">
                  <RedoOutlined
                    style={{ fontSize: 18, cursor: 'pointer' }}
                    onClick={refresh}
                  />
                </Tooltip>
                <Tooltip title="列设置">
                  <Dropdown overlay={columnsMenu} trigger={['click']}>
                    <SettingOutlined style={{ fontSize: 18 }} />
                  </Dropdown>
                </Tooltip>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </div>
  );

  const searchFrom = (
    <div style={{ marginBottom: 16 }}>
      <Form form={form} style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Form.Item name="gender">
          <Select
            style={{ width: 120, marginRight: 16 }}
            onChange={submit}
            placeholder="请选择性别"
          >
            <Option value="">全部</Option>
            <Option value="male">男</Option>
            <Option value="female">女</Option>
          </Select>
        </Form.Item>
        <Form.Item name="name">
          <Input
            placeholder="请输入姓名(防抖实时查询)"
            style={{ width: 240 }}
            onChange={run}
          />
        </Form.Item>
        <Button type="link" onClick={changeType}>
          更多操作
        </Button>
      </Form>
    </div>
  );

  return (
    <div>
      {type === 'simple' ? searchFrom : advanceSearchForm}
      <Table
        {...tableProps}
        dataSource={newColumns.length > 0 ? tableProps.dataSource : []}
        id="FullScreen-Table"
        rowKey="id"
        columns={newColumns}
        size={size[0]}
      />
    </div>
  );
};

useFormTablePage.title = 'useFormTable 使用';

export default useFormTablePage;
